'use strict'

let models = require('../models');
let errors = require('../../config/errors');

let Student = models.Student;
let School = models.School;
let Grade = models.Grade;
let NatureClass = models.NatureClass;
let Card = models.Card;
let AbsenceApply = models.AbsenceApply;
let AbsenceApplyStatus = models.AbsenceApplyStatus;

let StudentDao = models.StudentDao;
let SchoolDao = models.SchoolDao;
let GradeDao = models.GradeDao;
let NatureClassDao = models.NatureClassDao;
let UserDao = models.UserDao;
let CardDao = models.CardDao;
let AbsenceApplyDao = models.AbsenceApplyDao;

let userService = require('./user');

function createStudent(sid, name) {
    let user = userService.createUserOfRole(name, 'e10adc3949ba59abbe56e057f20f883e', 'student');
    return new Student({
        sid: sid,
        name: name,
        user: user,
        cards: [],
        attendCount: 0,
        totalAbsence: 0,
        lateCount: 0,
        absenceCount: 0,
        restCount: 0,
        earlyCount: 0
    });
}

function fromCsvData(csvData) {
    let csvLines = csvData.split('\n').slice(1).filter(line => line.trim().length > 0);
    let students = csvLines.map(csvLine => {
        let fields = csvLine.split(',');
        let user = userService.createUserOfRole(fields[0], 'e10adc3949ba59abbe56e057f20f883e', 'student');
        return new Student({
            sid: fields[0],
            name: fields[1],
            user: user,
            cards: [],
            attendCount: 0,
            totalAbsence: 0,
            lateCount: 0,
            absenceCount: 0,
            restCount: 0,
            earlyCount: 0
        });
    });

    return students;
}

function getStudentByUserId(userId) {
    return StudentDao.findOne({
        user: userId
    });
}

function getStudentByIFlyId(iflyId) {
    console.log(iflyId);
    let user = UserDao.findOne({
        iflyId: iflyId
    });

    return getStudentByUserId(user.id);
}

function submitAbsenceApply(student, data) {
    let absenceApply = new AbsenceApply({
        status: AbsenceApplyStatus.Processing,
        start: data.start,
        end: data.end,
        student: student,
        comment: data.comment
    });

    AbsenceApplyDao.create(absenceApply);

    return absenceApply;
}

function getGradeOfStudent(student) {
    let natureClass = NatureClassDao.findOne({
        students: student.id
    });

    let grade = GradeDao.findOne({
        natureClasses: natureClass.id
    });

    return grade;
}

function getSchoolOfStudent(student) {
    let grade = getGradeOfStudent(student);
    let school = SchoolDao.findOne({
        grades: grade.id
    });

    return school;
}

module.exports = {
    fromCsvData,
    createStudent,
    getStudentByUserId,
    submitAbsenceApply,
    getStudentByIFlyId,
    getGradeOfStudent,
    getSchoolOfStudent
};
